package org.hy.controller.basic;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.hy.domain.User;
import org.hy.domain.group.GDiscuss;
import org.hy.service.simple.IUserService;
import org.hy.util.AppConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
 * 用户控制器
 * @author xwm
 *
 */
@Controller
@RequestMapping("/")
public class UserController {
	//保存cookie的信息
	private static final String COOKIE_KEY = "uid";
	private static final String COOKIE_PATH = "/hy_2";
	private static final int COOKIE_TIME = 3600 * 24 * 7;
	
	@Autowired
	private IUserService userService;
	
	/**
	 *  关联index.vm模版视图
	 * @return 逻辑视图名称
	 */
	@RequestMapping("index")
	public String index() {
		return "index";
	}
	
	/**
	 * 处理登录
	 * @param email 用户账号,此参数从表单输入,然后被spring自动绑定,转型,然后注入到方法中
	 * @param password 密码,此参数从表单输入...
	 * @param rememberMe 是否使用cookie保存账号信息,当客户端未选中时,此参数为默认值false.
	 * @param session    http session对象
	 * @param redirectAttrs 用于页面跳转时传递参数
	 * @param encryptUid cookie中保存的用户id信息
	 * @param response http response对象,用于保存cookie信息
	 * @return 逻辑视图名称
	 */
	//@RequestMapping(value={"login"},method={RequestMethod.POST})
	public String login(String email,String password,@RequestParam(value="rememberMe",required=false,defaultValue="0")boolean rememberMe,HttpSession session,RedirectAttributes redirectAttrs,@CookieValue(value="uid",defaultValue="")String encryptUid,HttpServletResponse response) {
		User user = null;
		//从session登录
		
		//从cookie登录
		if(!StringUtils.isEmpty(encryptUid)){
			//省略解密操作
			int uid = Integer.parseInt(encryptUid);
			user = userService.findUserById(uid);
		}else { //根据用户输入登录
			user = userService.verify(email, password);
			if(rememberMe){  //添加cookie信息
				addCookie(response, user);
			}else{
				//deleteCookie(request, response, user);
			}
		}
		
		if(user != null) { //登录成功
			session.setAttribute(AppConstant.SESSION_KEY_USER, user);
			redirectAttrs.addFlashAttribute("success", "登录成功");
		}else {
			redirectAttrs.addFlashAttribute("error", "用户名或密码不正确!");
			return "redirect:index";  //重定向至index视图
		}
		return "redirect:home"; //重定向至home视图
	}
	
	@RequestMapping(value={"login"},method={RequestMethod.POST})
	public String login(User command,@RequestParam(value="rememberMe",required=false,defaultValue="0")boolean rememberMe,HttpSession session,RedirectAttributes redirectAttrs,@CookieValue(value="uid",defaultValue="")String encryptUid,HttpServletResponse response) {
		User user = null;
		//从session登录
		
		//从cookie登录
		if(!StringUtils.isEmpty(encryptUid)){
			//省略解密操作
			int uid = Integer.parseInt(encryptUid);
			user = userService.findUserById(uid);
		}else { //根据用户输入登录
			user = userService.verify(command.getEmail(), command.getPassword());
			if(rememberMe){  //添加cookie信息
				addCookie(response, user);
			}else{
				//deleteCookie(request, response, user);
			}
		}
		
		if(user != null) { //登录成功
			session.setAttribute("user", user);
			redirectAttrs.addFlashAttribute("success", "登录成功");
		}else {
			redirectAttrs.addFlashAttribute("error", "用户名或密码不正确!");
			return "redirect:index";  //重定向至index视图
		}
		return "redirect:home"; //重定向至home视图
	}
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping("home")
	public String home() {
		return "home";
	}
	
	/**
	 * 处理注册表单,注意请求为post
	 * @return 注册后跳转的页面
	 */
	@RequestMapping(value={"/register"},method={RequestMethod.POST})
	public String register() {
		
		return "index";
	}
	
	/**
	 * 注册页面,注意请求为get
	 * @return register视图名称
	 */
	@RequestMapping(value={"register"},method={RequestMethod.GET})
	public String newUser() {
		return "register";
	}
	
	//处理退出
	@RequestMapping("exit")
	public String exit(HttpSession session,RedirectAttributes redirectAttrs,HttpServletRequest request,HttpServletResponse response) {
		User user = (User)session.getAttribute("user");
		if(user != null){
			//清除session信息
			session.setAttribute("user", null);
			//删除cookie信息
			deleteCookie(request,response,user);
			redirectAttrs.addFlashAttribute("exitStatus","成功退出!");
		}
		return "redirect:index";
	}
	
	//添加cookie信息
	private void addCookie(HttpServletResponse response,User user){
		String encryptedUid = ""+user.getId();
		Cookie cookie = new Cookie(COOKIE_KEY,encryptedUid);
		cookie.setPath(COOKIE_PATH);
		cookie.setMaxAge(COOKIE_TIME);
		response.addCookie(cookie);
	}
	
	//删除cookie信息
	private void deleteCookie(HttpServletRequest request,HttpServletResponse response,User user){
		Cookie[] allCookie = request.getCookies();
		for (Cookie ck : allCookie) {
			if(COOKIE_KEY.equalsIgnoreCase(ck.getName())){
				ck.setValue(null);
				ck.setMaxAge(0);
				response.addCookie(ck);
			}
		}
	}
	
	@RequestMapping("/injection")
	public void nestParameterInjection(GDiscuss discuss){
		System.out.println(discuss);
	}
	
}
